const { exec, escape } = require('../db/mysql')
const { genPassword } = require('../utils/cryp')
const xss = require('xss')

const login = async (username, password) => {
    username = escape(username) 
    // 生成加密密码
    password = genPassword(password)
    password = escape(password) 
    const sql = `select id,username from users where username=${username} and password=${password}` 
    const rows = await exec(sql)
    return rows[0] || {}
} 

const register = async (username, password) => {
    username = escape(username) 
    // 生成加密密码
    password = genPassword(password)
    password = escape(password) 
    const sql = `insert into users (username,password,cover_thumb,birthdate) values(${username} , ${password},'http://img.zhichiwangluo.com/zc_app_default_photo.png',now());`  
    const insertData = await exec(sql)
    return {
        id: insertData.insertId
    }
}

const countUser = async (username) => {  
    const sql = `select count(*) AS count  from users where username='${username}';`  
	const rows = await exec(sql)
	return rows[0].count
}

const getDetail = async (id) => {
    const sql = `select id,username,nickname,sex,cover_thumb,phone,date_format(birthdate, '%Y-%m-%d') AS birthdate,address  from users where id = ${id};`
    const rows = await exec(sql)
    return rows[0]
}

const updateUser = async (userData = {}) => {   
    const id = xss(userData.id)
    const nickname = xss(userData.nickname)
    const sex = xss(userData.sex)
    const cover_thumb = xss(userData.cover_thumb)
    const phone = xss(userData.phone)
    const birthdate = xss(userData.birthdate)
    const address = xss(userData.address)

    const sql = `update users set nickname='${nickname}', sex='${sex}', cover_thumb='${cover_thumb}', phone='${phone}', birthdate='${birthdate}' , address='${address}' where id = ${id};` 
    const updateData = await exec(sql)
    if (updateData.affectedRows > 0) {
        return true
    }
    return false
}
module.exports = {
    login,
	register,
	countUser,
	getDetail,
	updateUser
}